package com.ruige.service.template;

import com.ruige.service.pojo.Result;
import com.ruige.service.pojo.Service;
import com.ruige.service.utils.URLUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

@Component
public class RuigeTemplate {

    @Autowired
    private RestTemplate restTemplate;


    /**
     * 注册服务
     *
     * @param gorekaAddr
     * @param method
     * @param service
     */
    public void register(String gorekaAddr, String method, Service service) {
        String url = URLUtils.toGoreka(gorekaAddr, method);
        Result result = null;
        try {
            result = restTemplate.postForObject(url, service, Result.class);
        } catch (RestClientException e) {
            System.out.println("注册服务异常!");
            e.printStackTrace();
        }
        System.out.println("当前服务: <" + service.getService_name() +"> "+ "注册反馈信息: " + result);
    }

    /**
     * 发送心跳
     *
     * @param gorekaAddr
     * @param method
     * @param service
     */
    public void ping(String gorekaAddr, String method, Service service) {
        String url = URLUtils.toGoreka(gorekaAddr, method);
        Result result = null;
        try {
            result = restTemplate.postForObject(url, service, Result.class);
            if (!result.getFlag()) {
                System.out.println("ping: 当前服务名:  <" + service.getService_name() +" >"+ result.getInfo() + "续约失败,启动重新注册程序!");
                this.register(gorekaAddr, "add", service);
            }
            System.out.println("ping: 当前服务名: <" + service.getService_name()+">  "+ result.getInfo());
        } catch (RestClientException e) {
            System.out.println("心跳服务异常!");
            e.printStackTrace();
        }
    }


    /**
     * 查找服务
     *
     * @param gorekaAddr
     * @param method
     * @return
     */
    public Result findAll(String gorekaAddr, String method) {
        String url = URLUtils.toGoreka(gorekaAddr, method);
        Result result = null;
        try {
            result = restTemplate.getForObject(url, Result.class);
        } catch (RestClientException e) {
            e.printStackTrace();
        }
        return result;
    }

}
